package com.example.demo.service;

import com.example.demo.mapper.ImgMapper;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

@Service
public class downService {
    /**
     * 下载模板
     *
     * @param response
     * @return
     */
    public String FILEPATH;

    @Autowired
    ImgMapper imgMapper;

    public void downTemplateInfo(HttpServletResponse response, String id) {
        String a = imgMapper.resolves(id);
        System.out.println("a"+a);


        FILEPATH = "F:/filepath/" + a.substring(32);
        try {
            downloadFile(FILEPATH, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void downloadFile(String filePath, HttpServletResponse response) throws Exception {
        File f = new File(filePath);
        if (!f.exists()) {
            throw new FileNotFoundException("找不到文件");
        }
        BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
        byte[] buf = new byte[1024];
        int len = 0;
        response.reset();
        response.setContentType("application/x-msdownload");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(f.getName(), "utf-8"));
        OutputStream out = response.getOutputStream();
        while ((len = br.read(buf)) > 0)
            out.write(buf, 0, len);
        IOUtils.closeQuietly(br);
        IOUtils.closeQuietly(out);
    }
}
